<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>插入数据</title>
    <link rel="stylesheet" href="./style.css" />
</head>

<body>
    <form action="http://127.0.0.1:8888/v2/addUser" id="myForm" method="post" class="form-example">
        <div class="form-control">
            <input type="text" name="username" autofocus autocomplete="false" required id="username" />
            <label for="username">
                <span style="transition-delay: 0ms">U</span><span style="transition-delay: 50ms">s</span><span
                    style="transition-delay: 100ms">e</span><span style="transition-delay: 150ms">r</span><span
                    style="transition-delay: 200ms">n</span><span style="transition-delay: 250ms">a</span><span
                    style="transition-delay: 300ms">m</span><span style="transition-delay: 350ms">e</span>
            </label>
        </div>
        <div class="form-control">
            <input type="password" name="password" id="password" required />
            <label for="password">
                <span style="transition-delay: 0ms">P</span><span style="transition-delay: 50ms">a</span><span
                    style="transition-delay: 100ms">s</span><span style="transition-delay: 150ms">s</span><span
                    style="transition-delay: 200ms">w</span><span style="transition-delay: 250ms">o</span><span
                    style="transition-delay: 300ms">r</span><span style="transition-delay: 350ms">d</span>
            </label>
        </div>
        <div class="form-control">
            <input type="email" name="email" autocomplete="false" id="email" required />
            <label for="username">
                <span style="transition-delay: 0ms">E</span><span style="transition-delay: 50ms">m</span><span
                    style="transition-delay: 100ms">a</span><span style="transition-delay: 150ms">l</span><span
                    style="transition-delay: 200ms">l</span>
            </label>
        </div>
        <div class="form-control">
            <input type="tel" name="telphone" id="telphone" required />
            <label for="telphone">
                <span style="transition-delay: 0ms">T</span><span style="transition-delay: 50ms">e</span><span
                    style="transition-delay: 100ms">l</span><span style="transition-delay: 150ms">p</span><span
                    style="transition-delay: 200ms">h</span><span style="transition-delay: 250ms">o</span><span
                    style="transition-delay: 300ms">n</span><span style="transition-delay: 350ms">e</span>
            </label>
        </div>
        <div class="form-button">
            <button type="submit" class="sub-button">Subscribe</button>
            <button type="button" class="refresh-button" id="refresh">
                <span class="button__text">Refresh</span>
                <span class="button__icon"><svg class="svg" height="48" viewBox="0 0 48 48" width="48"
                        xmlns="http://www.w3.org/2000/svg">
                        <path
                            d="M35.3 12.7c-2.89-2.9-6.88-4.7-11.3-4.7-8.84 0-15.98 7.16-15.98 16s7.14 16 15.98 16c7.45 0 13.69-5.1 15.46-12h-4.16c-1.65 4.66-6.07 8-11.3 8-6.63 0-12-5.37-12-12s5.37-12 12-12c3.31 0 6.28 1.38 8.45 3.55l-6.45 6.45h14v-14l-4.7 4.7z">
                        </path>
                        <path d="M0 0h48v48h-48z" fill="none"></path>
                    </svg></span>
            </button>
        </div>
    </form>
    <table border="0">
        <thead>
            <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>邮箱</th>
                <th>手机号</th>
                <th>注册时间</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody class="user-item" id="userTableBody"></tbody>
    </table>
</body>
<script>
    var currentEditUUID = null;

    // 表单提交事件
    document
        .getElementById("myForm")
        .addEventListener("submit", function (event) {
            event.preventDefault(); // 阻止表单的默认提交行为

            // 获取表单数据
            var formData = {
                username: document.getElementById("username").value,
                password: document.getElementById("password").value,
                email: document.getElementById("email").value,
                telphone: document.getElementById("telphone").value,
                uuid: currentEditUUID ? currentEditUUID : null
            };

            // 判断是添加操作还是修改操作
            var url = currentEditUUID
                ? "http://127.0.0.1:8888/v2/updateUser"
                : "http://127.0.0.1:8888/v2/addUser";

            // 发送请求
            fetch(url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(formData), // 将数据转换为JSON字符串
            })
                .then((response) => response.json()) // 解析 JSON 响应
                .then((data) => {
                    if (data.code === 200) {
                        getList();
                        currentEditUUID = null;
                        alert(data.msg);
                    } else {
                        alert(data.msg);
                    }
                })
                .catch((error) => {
                    console.error("Error:", error);
                });
        });
    var dataList = [];
    function getList() {
        fetch("http://127.0.0.1:8888/v2/getUserList")
            .then((response) => response.json()) // 解析 JSON 响应
            .then((res) => {
                console.log("data", res.data);
                let tableBody = "";
                // 对res.data的数据进行时间倒序排序
                res.data.sort((a, b) => {
                    return new Date(b.add_date) - new Date(a.add_date);
                });
                res.data.forEach((item) => {
                    tableBody += `
                <tr>
                    <td>${item.uuid}</td>
                    <td>${item.username}</td>
                    <td>${item.email}</td>
                    <td>${item.telphone}</td>
                    <td>${new Date(item.add_date).toLocaleString()}</td>
                    <td>
                        <button onclick="deleteUser('${item.uuid
                        }')" class="delete-button">删除</button>
                        <button class="update-button" data-uuid="${item.uuid
                        }" data-item='${JSON.stringify(item)}'>修改</button>
                    </td>
                </tr>`;
                });
                //重置表单
                resetForm()
                document.getElementById("userTableBody").innerHTML = tableBody;
                bindUpdateButtons(); // 给修改按钮绑定事件
            })
            .catch((error) => {
                console.error("Error:", error); // 错误处理
                document.getElementById("response").innerHTML = error;
            });
    }
    getList();
    // 刷新按钮点击事件
    document.getElementById("refresh").addEventListener("click", function () {
        getList();
    });
    /**
     * @description 删除用户
     * @param {string} uuid 用户uuid 必传
     */
    function deleteUser(uuid) {
        fetch("http://127.0.0.1:8888/v2/deleteUser?uuid=" + uuid, {
            method: "GET",
        })
            .then((response) => response.json()) // 解析 JSON 响应
            .then((data) => {
                if (data.code === 200) {
                    getList();
                    alert(data.msg);
                } else {
                    alert(data.msg);
                }
            })
            .catch((error) => {
                console.error("Error:", error);
            });
    }
    /**
     * @description 修改用户信息
     * @author long
     */
    function updateUser(uuid, item) {
        // 设置当前编辑的UUID
        currentEditUUID = uuid;
        // 填充表单
        document.getElementById("username").value = item.username;
        document.getElementById("email").value = item.email;
        document.getElementById("telphone").value = item.telphone;
        // 禁用密码输入框
        var passwordField = document.getElementById("password");
        if (passwordField) {
            passwordField.disabled = true;
            passwordField.required = false;
        }
    }
    // 每次用户点击修改时，调用updateUser函数
    function bindUpdateButtons() {
        document.querySelectorAll(".update-button").forEach((button) => {
            button.addEventListener("click", function () {
                var uuid = this.getAttribute("data-uuid");
                var item = JSON.parse(this.getAttribute("data-item"));
                updateUser(uuid, item);
            });
        });
    }
    /**
     * @description 重置表单 
     * @author long
     */
    function resetForm() {
        // 重置全局变量
        currentEditUUID = null;
        // 清空表单字段
        document.getElementById("myForm").reset();
        // 启用密码输入框
        var passwordField = document.getElementById("password");
        if (passwordField) {
            passwordField.disabled = false;
        }
    }
</script>

</html>